// pages/community/search/search.js
const storeService = require('../../../../api/storeService.js')
const productService = require('../../../../api/productService.js')
const util = require('../../../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    storeId: '',
    store: '',
    page: 1,
    pageSize: 0,
    searchCount: true,
    searchLabelShow: false,
    searchFocus: true,
    searchText: '搜索感兴趣的内容',
    searchItem: "",
    goodsList: [],
    hotsSearch: ['西瓜','水果'],
    nameLikes: '',
    keyboardHeight: 0,
    recorderType: 'normal' //normal (正常) success (成功) fail (失败) cancel (取消)
  },

  // 搜索框点击事件,输入框聚焦
  handleFocus: function (e) {
    this.setData({
      searchLabelShow: true,
      goodsList: [],
    })
  },
  // 搜索框聚焦事件
  handleInputFocus: function (e) {
    console.log(e.detail)
    this.setData({
      keyboardHeight: e.detail.height
    })
  },
  // 搜索框失去焦点处理
  handleBlur: function (e) {
    if (!e.detail.value) {
      this.setData({
        searchLabelShow: false,
        goodsList: [],
        keyboardHeight: 0
      })
    } else {
      this.setData({
        keyboardHeight: 0
      })
    }
  },
  // 搜索框失去焦点处理
  handleBlur: function (e) {
    if (!e.detail.value) {
      this.setData({
        searchLabelShow: false,
        goodsList: [],
      })
    }
  },
  // 输入框输入时处理
  handleInput: function (e) {
    this.setData({
      nameLikes: e.detail.value
    })
  },
  toSearch: function () {
    let nameLikes = this.data.nameLikes
    if (!nameLikes) {
      wx.showToast({
        title: '请输入您想搜索的商品名称！',
        icon: "none",
        duration: 2000
      })
    } else {
      nameLikes = nameLikes.replace(/(^\s*)|(\s*$)/g, "");
      this.setData({
        searchItem: nameLikes,
        searchLabelShow: true
      })
      this.getSearchProduct(nameLikes)
    }
  },
  // 搜索框失去焦点处理
  handleConfirm: function (e) {
    console.log(e)
    if (!e.detail.value) {
      this.setData({
        searchLabelShow: false,
        keyboardHeight: 0
      })
      wx.showToast({
        title: '请输入您想搜索的商品名称！',
        icon: "none",
        duration: 2000
      })
    } else {
      var nameLikes = e.detail.value.replace(/(^\s*)|(\s*$)/g, "");
      this.getSearchProduct(nameLikes)
    }
  },
  getSearchProduct: function (nameLikes) {
    var storeId = this.data.storeId;
    const that = this
    var page = this.data.page;
    var pageSize = this.data.pageSize;
    var searchCount = this.data.searchCount;
    console.log(nameLikes)
    productService.getSearchProduct(storeId, page, pageSize, nameLikes, searchCount).then(res => {
      console.log(res);
      let tempList = []
      if (res.records && res.records.length > 0) {
        res.records.forEach(item => {
          let produtlabel = []
          let promotions = []
          let specifications = ''
          if (item.labels && item.labels.length > 0) {
            item.labels.forEach(ele => {
              if (ele.type === 'GOODSLABEL') {
                produtlabel.push(ele)
              } else if (ele.type === 'PROMOTIONLABEL') {
                promotions.push(ele)
              }
            })
          }
          if (item.productProperties && item.productProperties.length > 0) {
            for (let i = 0; i < item.productProperties.length; i++) {
              const ele = item.productProperties[i];
              if (ele.propertyName === '规格') {
                specifications = ele.propertyValue
                break
              }
            }
          }
          let tempItem = {
            ...item,
            produtlabel: produtlabel,
            promotions: promotions,
            specifications: specifications
          }
          tempList.push(tempItem)
        })
        that.setData({
          goodsList: tempList
        })
      } else {
        wx.showToast({
          title: '没有您想搜索的商品！',
          icon: "none",
          duration: 2000
        })
      }
    })
    this.sethotsSearch(nameLikes)
  },
  // 设置搜索历史缓存及数组
  sethotsSearch: function (nameLikes) {
    var searchData = this.data.hotsSearch;
    searchData.unshift(nameLikes);
    var newSetData = new Set(searchData);
    var newSearchData = Array.from(newSetData);
    wx.setStorageSync('hotsSearchDataLog', newSearchData);
    var SearchDataCache = newSearchData.slice(0, 10)
    this.setData({
      hotsSearch: SearchDataCache
    })
  },
  toGoodsDetail: function (val) {
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?productId=' + val.currentTarget.id + '&storeId=' + this.data.storeId + '&type=normal'
    })
  },
  // 点击搜索记录
  clickSearchItem: function (e) {
    const that = this;
    that.handleFocus();
    that.setData({
      searchItem: e.currentTarget.dataset.value,
      nameLikes: e.currentTarget.dataset.value
    })
    var nameLikes = that.data.searchItem
    that.getSearchProduct(nameLikes)
  },
  // 清除历史记录
  clearhotsSearch: function () {
    const that = this;
    wx.removeStorageSync('hotsSearchDataLog')
    that.setData({
      hotsSearch: []
    })
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const self = this;
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      self.setData({
        store: app.globalData.storeInfo.name,
        storeId: app.globalData.storeInfo.id
      })
    }
    else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          var speed = res.speed
          var accuracy = res.accuracy

          try {
            var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
            if (tempAllStores) {
              // Do something with return value
              let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
              app.globalData.storeInfo = tempAllStores[tempIndex];
            } else {
              // 查询所有门店
              storeService.queryList().then(res => {
                var allStores = res;
                try {
                  wx.setStorageSync('wj_allStores', allStores)
                } catch (e) {
                  console.log(e)
                }
                let tempIndex = self.getNearestStore(allStores, latitude, longitude);
                return allStores[tempIndex]
              }).then(res => {
                app.globalData.storeInfo = res;
                self.getMenuProduct(res.id)
              })
            }
          } catch (e) {
            // Do something when catch error
          }
        }
      })
    }
    if (options.keyword && options.type === 'atOnce') {
      self.handleFocus()
      if ("" != wx.getStorageSync('hotsSearchDataLog')) {
        self.setData({
          hotsSearch: wx.getStorageSync('hotsSearchDataLog').slice(0, 10),
          searchItem: options.keyword,
          nameLikes: options.keyword
        });
      } else {

      }
      self.getSearchProduct(options.keyword)
    } else if (options.keyword && options.type === 'wait') {
      self.handleFocus()
      if ("" != wx.getStorageSync('hotsSearchDataLog')) {
        self.setData({
          hotsSearch: wx.getStorageSync('hotsSearchDataLog').slice(0, 10),
        });
      } else {

      }
      self.setData({
        // searchItem: options.keyword,
        nameLikes: options.keyword
      })
    } else {
      self.handleFocus()
      if ("" != wx.getStorageSync('hotsSearchDataLog')) {
        self.setData({
          hotsSearch: wx.getStorageSync('hotsSearchDataLog').slice(0, 10)
        });
      } else {

      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})